package wpwork.controller;


import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import wpwork.base.ActionResult;
import wpwork.base.UserInfo;
import wpwork.base.controller.SuperController;
import wpwork.base.vo.PageListVO;
import wpwork.entity.*;
import wpwork.model.*;
import wpwork.permission.entity.UserEntity;
import wpwork.permission.mapper.UserMapper;
import wpwork.service.*;
import wpwork.service.impl.DataInteractionService;
import wpwork.util.ServletUtil;
import wpwork.util.UserProvider;

import javax.validation.Valid;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static cn.dev33.satoken.dao.SaTokenDaoRedisJackson.TIME_FORMATTER;
import static cn.hutool.core.bean.BeanUtil.copyProperties;

/**
 * Contract
 * 版本： V3.0.0
 * 版权： 武汉维普科技有限公司(https://www.websharp.cn)
 * 作者： wpwork开发平台组
 * 日期： 2020-12-31
 * 巡检配置
 */
@RestController
@Slf4j
@Tag(name = "示例接口", description = "WorkPersonJob")
@RequestMapping("/api/example/WorkPersonJob")
public class WorkPersonJobController extends SuperController<WorkPersonJobService, WorkPersonJobEntity> {

    @Autowired
    private WorkPersonJobService workPersonJobService; // 确保 service 已注入
    @Autowired
    private WorkRsattendanceService workRsattendanceService;
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private WorkResourcesService workResourcesService;
    @Autowired
    private WorkRsinspectionService workRsinspectionService;
    @Autowired
    private WorkRsfenceService workRsfenceService;
    @Autowired
    private WorkRsgridService workRsgridService;
    @Autowired
    private UserMapper userMapper;

    //Redis发布于
    @Autowired
    private DataInteractionService dataInteractionService;

    @Operation(summary = "添加定时数据")
    @PostMapping("/dailyTaskAtNoon")
    public ActionResult<?> list() {
        dailyTaskAtNoon();
        return null;
    }

    @Scheduled(cron = "0 0 23 * * ?", zone = "Asia/Shanghai")
    public void dailyTaskAtNoon() {
        System.out.println("定时任务执行：当前时间 = " + LocalDateTime.now());

        // 1. 查询所有有效的、未删除的考勤配置
        LambdaQueryWrapper<WorkRsattendanceEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WorkRsattendanceEntity::getEnabledMark, 1)
                .isNotNull(WorkRsattendanceEntity::getTerminal)
                .isNotNull(WorkRsattendanceEntity::getTime);

        List<WorkRsattendanceEntity> attendanceList = workRsattendanceService.list(queryWrapper);
        for (WorkRsattendanceEntity attendance : attendanceList) {
            addAttendanceJob(attendance,1);
        }


        // 2. 查询所有有效的、未删除的巡检配置
        LambdaQueryWrapper<WorkRsinspectionEntity> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(WorkRsinspectionEntity::getEnabledMark, 1)
                .isNotNull(WorkRsinspectionEntity::getTerminal)
                .isNotNull(WorkRsinspectionEntity::getTime);

        List<WorkRsinspectionEntity> rsinspectionList = workRsinspectionService.list(queryWrapper2);
        for (WorkRsinspectionEntity rsinspection : rsinspectionList) {
            addRsinspectionJob(rsinspection ,1);
        }

        // 3. 查询所有有效的、未删除的围栏配置
        LambdaQueryWrapper<WorkRsfenceEntity> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.eq(WorkRsfenceEntity::getEnabledMark, 1)
                .isNotNull(WorkRsfenceEntity::getTerminal)
                .isNotNull(WorkRsfenceEntity::getTime);

        List<WorkRsfenceEntity> rsfenceEntities = workRsfenceService.list(queryWrapper3);
        for (WorkRsfenceEntity rsfence : rsfenceEntities) {
            addRsfenceJob(rsfence,1);
        }

        // 4. 查询所有有效的、未删除的网格配置
        LambdaQueryWrapper<WorkRsgridEntity> queryWrapper4 = new LambdaQueryWrapper<>();
        queryWrapper4.eq(WorkRsgridEntity::getEnabledMark, 1)
                .isNotNull(WorkRsgridEntity::getTerminal)
                .isNotNull(WorkRsgridEntity::getTime);

        List<WorkRsgridEntity> rsgridEntities= workRsgridService.list(queryWrapper4);
        for (WorkRsgridEntity rsgrid : rsgridEntities) {
            addRsgridJob(rsgrid,1);
        }


        System.out.println("【定时任务结束】" + LocalDateTime.now());
    }

    @PostMapping("/getOne")
    public ActionResult<WorkPersonJobEntity> getOne(@RequestParam String id) {
        WorkPersonJobEntity entity = workPersonJobService.getById(id);
        return ActionResult.success(entity);
    }


    @Operation(summary = "获取列表")
    @PostMapping("/List")
    public ActionResult<?> list(@RequestParam String id,@RequestParam String type) {
        QueryWrapper<WorkPersonJobEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("f_job_user_id", id).eq("f_type",type).orderByDesc("f_execution_date");
        List<WorkPersonJobEntity> list = workPersonJobService.list(queryWrapper);
        return ActionResult.success(list);
    }

    @Operation(summary = "考勤统计")
    @PostMapping("/attendanceStatistics")
    public ActionResult<?> attendanceStatistics(@RequestParam String startTime,@RequestParam String endTime,@RequestParam String name) {
        List<WorkPersonJobVO> list = workPersonJobService.homeStatistics("考勤",startTime,endTime,name);
        return ActionResult.success(list);
    }

    @Operation(summary = "巡检统计")
    @PostMapping("/inspectionStatistics")
    public ActionResult<?> inspectionStatistics(@RequestParam String startTime,@RequestParam String endTime,@RequestParam String name) {
        List<WorkPersonJobVO> list = workPersonJobService.homeStatistics("巡检",startTime,endTime,name);
        return ActionResult.success(list);
    }
    @Operation(summary = "事件统计")
    @PostMapping("/eventStatistics")
    public ActionResult<?> eventStatistics(@RequestParam String startTime,@RequestParam String endTime,@RequestParam String name) {
        List<WorkPersonJobVO> list = workPersonJobService.homeStatisticsByExecutionDate("随手拍",startTime,endTime,name);
        return ActionResult.success(list);
    }

    @Operation(summary = "删除")
    @PostMapping("/deleteDataOne")
    public ActionResult<?> deleteDataOne(@RequestParam String id) {
        boolean b = workPersonJobService.removeById(id);
        if (b){
            return ActionResult.success("删除成功");
        }else{
            return ActionResult.fail("删除失败");
        }
    }

    //个人任务
    @PostMapping("/add")
    public ActionResult<WorkPersonJobEntity> add(@RequestBody @Valid WorkPersonJobEntity workPersonJob) {
        workPersonJob.setId(UUID.randomUUID().toString());
        workPersonJob.setCreatorTime(new Date());
        String jwtToken = ServletUtil.getRequest().getHeader("Authorization");
        UserInfo userInfo = userProvider.get(jwtToken);
        workPersonJob.setCreatorUserId(userInfo.getUserId());
        workPersonJob.setEnabledMark(1);
        workPersonJob.setExecutionStatus("未完成");

        boolean save = workPersonJobService.save(workPersonJob);
        if(save){
            UserEntity userEntity = userMapper.selectById(workPersonJob.getJobUserId());
            List<wpwork.redisEntity.UserInfo> userList = new ArrayList<>();
            userList.add(new wpwork.redisEntity.UserInfo(workPersonJob.getJobUserId(), userEntity.getAccount()));
            com.alibaba.fastjson.JSONObject jobInfoJson = com.alibaba.fastjson.JSONObject.parseObject(workPersonJob.getJobinfo());
            com.alibaba.fastjson.JSONObject option1 = jobInfoJson.getJSONObject("option1");
            String notes = option1.getString("notes");
            String body = option1.getString("body");
            String text = "任务标题"+notes + "任务内容"+ body;
            dataInteractionService.handleAICall("747384603941027201", text, userList);
            return ActionResult.success("添加成功");
        }else{
            return ActionResult.fail("添加失败");
        }
    }

    //协同任务
    @PostMapping("/addGroup")
    public ActionResult<?> addGroup(@RequestBody WorkPersonJobBatchDTO batchDTO) {
        try {
            String jwtToken = ServletUtil.getRequest().getHeader("Authorization");
            UserInfo userInfo = userProvider.get(jwtToken);

            List<WorkPersonJobEntity> jobEntities = new ArrayList<>();
            List<String> allUserIds = new ArrayList<>();

            // 合并普通用户和负责人，避免重复
            if (batchDTO.getUserIds() != null) {
                allUserIds.addAll(batchDTO.getUserIds());
            }
            if (batchDTO.getManagerIds() != null) {
                for (String managerId : batchDTO.getManagerIds()) {
                    if (!allUserIds.contains(managerId)) {
                        allUserIds.add(managerId);
                    }
                }
            }
            String taskNum = UUID.randomUUID().toString();
            // 为每个用户创建任务
            for (String userId : allUserIds) {
                WorkPersonJobEntity jobEntity = new WorkPersonJobEntity();

                // 手动复制属性（替代copyProperties）
                jobEntity.setId(UUID.randomUUID().toString());
                jobEntity.setCreatorTime(new Date());
                jobEntity.setCreatorUserId(userInfo.getUserId());
                jobEntity.setEnabledMark(1);
                jobEntity.setExecutionStatus("未完成");
                jobEntity.setJobUserId(userId);
                jobEntity.setTaskNumber(taskNum);
                jobEntity.setText(batchDTO.getText());
                // 从DTO复制任务相关信息
                jobEntity.setResourcesId(batchDTO.getResourcesId());
                jobEntity.setType(batchDTO.getType());
                jobEntity.setExecutionDate(batchDTO.getExecutionDate());
                jobEntity.setBegindate(batchDTO.getBegindate());
                jobEntity.setEnddate(batchDTO.getEnddate());
                jobEntity.setJobinfo(batchDTO.getJobinfo());

                jobEntity.setLocation(batchDTO.getLocation());
                if (batchDTO.getManagerIds() != null && batchDTO.getManagerIds().contains(userId)) {
                    jobEntity.setInstantperson(1); // 标记为负责人
                }else {
                    jobEntity.setInstantperson(0);
                }
                jobEntities.add(jobEntity);
            }

            boolean save = workPersonJobService.saveBatch(jobEntities);
            if(save){
                List<wpwork.redisEntity.UserInfo> userList = new ArrayList<>();
                for (WorkPersonJobEntity workPersonJob : jobEntities){
                    UserEntity userEntity = userMapper.selectById(workPersonJob.getJobUserId());
                    userList.add(new wpwork.redisEntity.UserInfo(workPersonJob.getJobUserId(), userEntity.getAccount()));
                }
                com.alibaba.fastjson.JSONObject jobInfoJson = com.alibaba.fastjson.JSONObject.parseObject(batchDTO.getJobinfo());
                com.alibaba.fastjson.JSONObject option1 = jobInfoJson.getJSONObject("option1");
                String notes = option1.getString("notes");
                String body = option1.getString("body");
                String text = "任务标题"+notes + "任务内容"+ body;
                dataInteractionService.handleAICall("747384603941027201",text, userList);
                return ActionResult.success("批量添加成功");
            }else{
                return ActionResult.fail("批量添加失败");
            }
        } catch (Exception e) {
            return ActionResult.fail("添加失败: " + e.getMessage());
        }
    }

    @PostMapping("/sspAdd")
    public ActionResult<WorkPersonJobEntity> sspAdd(@RequestBody @Valid WorkPersonJobEntity workPersonJob) {
        workPersonJob.setId(UUID.randomUUID().toString());
        workPersonJob.setType("随手拍");
//        workPersonJob.setCreatorTime(new Date());
        String jwtToken = ServletUtil.getRequest().getHeader("Authorization");
        UserInfo userInfo = userProvider.get(jwtToken);
        workPersonJob.setCreatorUserId(userInfo.getUserId());
        workPersonJob.setEnabledMark(1);
//        workPersonJob.setExecutionStatus("未完成");

        boolean save = workPersonJobService.save(workPersonJob);
        if(save){
            return ActionResult.success("添加成功");
        }else{
            return ActionResult.fail("添加失败");
        }
    }

    @Operation(summary = "获取随手拍任务列表")
    @PostMapping("/sspList")
    public ActionResult<List<WorkPersonJobEntity>> sspList(@RequestParam String id) {
        QueryWrapper<WorkPersonJobEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("f_type", "随手拍")
                .eq("f_enabled_mark", 1)
                .eq("f_creator_user_id", id)
                .orderByDesc("f_creator_time");
        List<WorkPersonJobEntity> list = workPersonJobService.list(queryWrapper);
        return ActionResult.success(list);
    }

    @Operation(summary = "修改随手拍任务")
    @PostMapping("/sspUpdate")
    public ActionResult<WorkPersonJobEntity> sspUpdate(@RequestBody @Valid WorkPersonJobEntity workPersonJob) {
        workPersonJob.setLastModifyTime(new Date());
        String jwtToken = ServletUtil.getRequest().getHeader("Authorization");
        UserInfo userInfo = userProvider.get(jwtToken);
        workPersonJob.setExecutionTime(new Date());
        workPersonJob.setLastModifyUserId(userInfo.getUserId());

        boolean update = workPersonJobService.updateById(workPersonJob);
        if(update){
            return ActionResult.success("修改成功");
        }else{
            return ActionResult.fail("修改失败");
        }
    }

    @PostMapping("/sspGetOne")
    public ActionResult<WorkPersonJobEntity> sspGetOne(@RequestParam String id) {
        WorkPersonJobEntity entity = workPersonJobService.getById(id);
        return ActionResult.success(entity);
    }

    @PostMapping("/getTaskListByUserId")
    public ActionResult<List<WorkPersonJobEntity>> getTaskListByUserId(@RequestParam String userId) {
        QueryWrapper<WorkPersonJobEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("f_job_user_id", userId)
                .eq("f_type", "协同任务")
                .eq("f_enabled_mark", 1)
                .orderByDesc("f_begindate");
        List<WorkPersonJobEntity> list = workPersonJobService.list(queryWrapper);
        return ActionResult.success(list);
    }

    @PostMapping("/getTaskListByUserId1")
    public ActionResult<List<WorkPersonJobEntity>> getTaskListByUserId1() {
        QueryWrapper<WorkPersonJobEntity> queryWrapper = new QueryWrapper<>();
//        .eq("f_job_user_id", userId)
        queryWrapper
                .in("f_type", "协同任务", "个人任务")  // 修改此处，使用 in 条件查询多个类型
                .eq("f_enabled_mark", 1)
                .orderByDesc("f_begindate");
        List<WorkPersonJobEntity> list = workPersonJobService.list(queryWrapper);
        return ActionResult.success(list);
    }

    @PostMapping("/getInfoByTaskNum")
    public ActionResult<List<TaskInfoVO>> getInfoByTaskNum(@RequestParam String taskNum) {
        List<TaskInfoVO> infoByTaskNum = workPersonJobService.getInfoByTaskNum(taskNum);
        return ActionResult.success(infoByTaskNum);
    }

    @PostMapping("/updateTask")
    public ActionResult<WorkPersonJobEntity> updateTask(@RequestBody @Valid WorkPersonJobEntity workPersonJob) {
        WorkPersonJobEntity entity = new WorkPersonJobEntity();
        entity.setId(workPersonJob.getId());
        entity.setExecutionStatus(workPersonJob.getExecutionStatus());
        entity.setExecutionTime(new Date());
        entity.setExecutionLocation(workPersonJob.getExecutionLocation());
        entity.setImageurl(workPersonJob.getImageurl());
        entity.setVideourl(workPersonJob.getVideourl());
        entity.setRemark(workPersonJob.getRemark());
        entity.setTaskNumber(workPersonJob.getTaskNumber());
        entity.setInstantperson(workPersonJob.getInstantperson());
        entity.setText(workPersonJob.getText());
        entity.setLocationDesc(workPersonJob.getLocationDesc());
        entity.setLastModifyTime(new Date());
        String jwtToken = ServletUtil.getRequest().getHeader("Authorization");
        UserInfo userInfo = userProvider.get(jwtToken);
        entity.setLastModifyUserId(userInfo.getUserId());
        boolean save = workPersonJobService.updateById(entity);
        try {
            if (workPersonJob.getInstantperson() == 1 && workPersonJob.getExecutionStatus().equals("已完成")){
                List<WorkPersonJobEntity> infoListByTaskNum = workPersonJobService.getInfoListByTaskNum(workPersonJob.getTaskNumber());
                for (WorkPersonJobEntity info : infoListByTaskNum) {
                    info.setExecutionStatus("已完成");
                    workPersonJobService.updateById(info);
                }
            }else if (workPersonJob.getInstantperson() == 1 && workPersonJob.getExecutionStatus().equals("未完成")){
                List<WorkPersonJobEntity> infoListByTaskNum = workPersonJobService.getInfoListByTaskNum(workPersonJob.getTaskNumber());
                for (WorkPersonJobEntity info : infoListByTaskNum) {
                    info.setExecutionStatus("未完成");
                    workPersonJobService.updateById(info);
                }
            }
        }catch (Exception e){
            return ActionResult.fail("负责人修改数据失败: " + e.getMessage());
        }

        if(save){
            return ActionResult.success("修改成功");
        }else{
            return ActionResult.fail("修改失败");
        }
    }

    @PostMapping("/page")
    public ActionResult<PageListVO<WorkPersonJobDTO>> getPage(@RequestBody WorkPersonJobQueryVO queryVO) {
        // 详细记录接收到的参数
        log.info("Controller接收到的查询参数: {}", queryVO.toString());
        log.info("Controller详细参数 - page: {}, size: {}, fType: '{}', fText: '{}', fExecutionStatus: '{}'",
                queryVO.getPage(), queryVO.getSize(), queryVO.getFType(),
                queryVO.getFText(), queryVO.getFExecutionStatus());

        PageListVO<WorkPersonJobDTO> result = workPersonJobService.getWorkPersonJobPage(queryVO);
        return ActionResult.page(result.getList(), result.getPagination());
    }

    @PostMapping("/page-debug")
    public ActionResult<?> getPageDebug(@RequestBody Map<String, Object> params) {
        log.info("原始接收的Map参数: {}", params);

        // 手动创建查询对象
        WorkPersonJobQueryVO queryVO = new WorkPersonJobQueryVO();

        if (params.get("page") != null) {
            queryVO.setPage(Integer.parseInt(params.get("page").toString()));
        }
        if (params.get("size") != null) {
            queryVO.setSize(Integer.parseInt(params.get("size").toString()));
        }
        if (params.get("fType") != null) {
            queryVO.setFType(params.get("fType").toString());
        }
        if (params.get("fText") != null) {
            String fText = params.get("fText").toString();
            queryVO.setFText("".equals(fText) ? null : fText);
        }

        if (params.get("fExecutionStatus") != null) {
            String fExecutionStatus = params.get("fExecutionStatus").toString();
            queryVO.setFExecutionStatus("".equals(fExecutionStatus) ? null : fExecutionStatus);
        }

        if (params.get("fRealName") != null) {
            String fRealName = params.get("fRealName").toString();
            queryVO.setFRealName("".equals(fRealName) ? null : fRealName);
        }

        PageListVO<WorkPersonJobDTO> result = workPersonJobService.getWorkPersonJobPage(queryVO);
        return ActionResult.page(result.getList(), result.getPagination());
    }




    @PostMapping("/update")
    public ActionResult<WorkPersonJobEntity> update(@RequestBody @Valid WorkPersonJobEntity workPersonJob) {
        WorkPersonJobEntity entity = new WorkPersonJobEntity();
        entity.setId(workPersonJob.getId());
        entity.setExecutionStatus(workPersonJob.getExecutionStatus());
        entity.setExecutionTime(new Date());
        entity.setExecutionLocation(workPersonJob.getExecutionLocation());
        entity.setImageurl(workPersonJob.getImageurl());
        entity.setVideourl(workPersonJob.getVideourl());
        entity.setText(workPersonJob.getText());
        entity.setLocationDesc(workPersonJob.getLocationDesc());
        entity.setJobinfo(workPersonJob.getJobinfo());
        entity.setRemark(workPersonJob.getRemark());

        entity.setLastModifyTime(new Date());
        String jwtToken = ServletUtil.getRequest().getHeader("Authorization");
        UserInfo userInfo = userProvider.get(jwtToken);
        entity.setLastModifyUserId(userInfo.getUserId());
        boolean save = workPersonJobService.updateById(entity);
        if(save){
            return ActionResult.success("修改成功");
        }else{
            return ActionResult.fail("修改失败");
        }
    }

    public void addAttendanceJob(WorkRsattendanceEntity attendance,int addDays){
        // 获取今天是星期几（1=周一, 7=周日）
        DayOfWeek today = LocalDateTime.now().plusDays(addDays).getDayOfWeek();
        String todayStr = String.valueOf(today.getValue()); // 转为字符串："1"~"7"
        // 使用 Hutool 解析 JSON 字符串
        JSONArray array = JSONUtil.parseArray(attendance.getTime());
        WorkResourcesEntity resources = workResourcesService.getById(attendance.getResourcesId());
        for (Object obj : array) {
            JSONObject item2 = (JSONObject) obj;
            String time = item2.getStr("time");
            LocalTime localTime = LocalTime.parse(time, java.time.format.DateTimeFormatter.ofPattern("HH:mm"));
            LocalDateTime dateTime = LocalDateTime.of(LocalDate.now().plusDays(addDays), localTime);
            Date date = Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant());
            String type = item2.getStr("type");
            String requirement = item2.getStr("requirement");
            List<String> weekdays = item2.getByPath("weekdays", List.class); // 自动转为 List<String>

            // 判断今天的星期是否在 weekdays 中
            if (weekdays.contains(todayStr)) {
                ObjectMapper mapper = new ObjectMapper();
                mapper.registerModule(new JavaTimeModule());
                List<Map<String, String>> listTerminal = null;
                try {
                    listTerminal = mapper.readValue(attendance.getTerminal(), new TypeReference<List<Map<String, String>>>() {});
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }

                WorkPersonJobEntity personJob = new WorkPersonJobEntity();
                personJob.setType("考勤");
                personJob.setResourcesId(resources.getId());
                personJob.setLocation(resources.getLocation());
                personJob.setExecutionDate(java.sql.Date.valueOf(LocalDate.now().plusDays(addDays)));
                personJob.setExecutionStatus("未完成");
                personJob.setText(resources.getName());
                if("before".equals(requirement)){
                    personJob.setBegindate(date);
                }else{
                    personJob.setEnddate(date);
                }
                Map<String, String> jobInfo = new HashMap<>();
                jobInfo.put("notes", resources.getRemark());
                jobInfo.put("isphoto", attendance.getMapupload() == 1 ? "是" : "否");
                jobInfo.put("distance", attendance.getDistance().toString());
                jobInfo.put("type", type);
                Map<String, Object> jobInfo2 = new HashMap<>();
                jobInfo2.put("option1", jobInfo);
                personJob.setJobinfo(com.alibaba.fastjson.JSONObject.toJSONString(jobInfo2));
                personJob.setEnabledMark(1);
                System.out.println("---");
                for (Map<String, String> item : listTerminal) {
                    System.out.println("key: " + item.get("key"));
                    System.out.println("label: " + item.get("label"));
                    System.out.println("---");
                    personJob.setJobUserId(item.get("key"));
                    personJob.setId(UUID.randomUUID().toString());

                    personJob.setCreatorTime(new Date());
//                    String jwtToken = ServletUtil.getRequest().getHeader("Authorization");
//                    UserInfo userInfo = userProvider.get(jwtToken);
//                    personJob.setCreatorUserId(userInfo.getUserId());
//                        QueryWrapper<WorkPersonJobEntity> query = new QueryWrapper<>();
//                        query.lambda().eq(WorkPersonJobEntity::getResourcesId, personJob.getResourcesId())
//                                .eq(WorkPersonJobEntity::getJobUserId, personJob.getJobUserId())
//                                .eq(WorkPersonJobEntity::getJobinfo, personJob.getJobinfo())
//                                .eq(WorkPersonJobEntity::getType, personJob.getType());
//                        List<WorkPersonJobEntity> list = workPersonJobService.list(query);
//                        if(list.size() == 0){
                    workPersonJobService.save(personJob);
//                        }
                }

            }
        }
    }
    public void addRsinspectionJob(WorkRsinspectionEntity rsinspection,int addDays) {
        // 获取今天是星期几（1=周一, 7=周日）
        DayOfWeek today = LocalDateTime.now().plusDays(addDays).getDayOfWeek();
        String todayStr = String.valueOf(today.getValue()); // 转为字符串："1"~"7"

        // 使用 Hutool 解析 JSON 字符串
        JSONArray array = JSONUtil.parseArray(rsinspection.getTime());
        WorkResourcesEntity resources = workResourcesService.getById(rsinspection.getResourcesId());
        for (Object obj : array) {
            JSONObject item2 = (JSONObject) obj;
            String time = item2.getStr("time");
            LocalTime localTime = LocalTime.parse(time, java.time.format.DateTimeFormatter.ofPattern("HH:mm"));
            LocalDateTime dateTime = LocalDateTime.of(LocalDate.now().plusDays(addDays), localTime);
            Date date = Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant());
            String type = item2.getStr("type");
            String requirement = item2.getStr("requirement");
            List<String> weekdays = item2.getByPath("weekdays", List.class); // 自动转为 List<String>

            // 判断今天的星期是否在 weekdays 中
            if (weekdays.contains(todayStr)) {
                ObjectMapper mapper = new ObjectMapper();
                mapper.registerModule(new JavaTimeModule());
                List<Map<String, String>> listTerminal = null;
                try {
                    listTerminal = mapper.readValue(rsinspection.getTerminal(), new TypeReference<List<Map<String, String>>>() {});
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }

                WorkPersonJobEntity personJob = new WorkPersonJobEntity();
                personJob.setType("巡检");
                personJob.setResourcesId(resources.getId());
                personJob.setLocation(resources.getLocation());
                personJob.setExecutionDate(java.sql.Date.valueOf(LocalDate.now().plusDays(addDays)));
                personJob.setExecutionStatus("未完成");
                personJob.setText(resources.getName());
                if("before".equals(requirement)){
                    personJob.setBegindate(date);
                }else{
                    personJob.setEnddate(date);
                }
                Map<String, String> jobInfo = new HashMap<>();
                jobInfo.put("notes", resources.getRemark());
                jobInfo.put("isphoto", rsinspection.getMapupload() == 1 ? "是" : "否");
                jobInfo.put("inspectionFeedback", rsinspection.getInspectionFeedback());
                jobInfo.put("type", type);
                Map<String, Object> jobInfo2 = new HashMap<>();
                jobInfo2.put("option1", jobInfo);
                personJob.setJobinfo(com.alibaba.fastjson.JSONObject.toJSONString(jobInfo2));
                personJob.setEnabledMark(1);
                System.out.println("---");
                for (Map<String, String> item : listTerminal) {
                    System.out.println("key: " + item.get("key"));
                    System.out.println("label: " + item.get("label"));
                    System.out.println("---");
                    personJob.setJobUserId(item.get("key"));
                    personJob.setId(UUID.randomUUID().toString());

                    personJob.setCreatorTime(new Date());
//                    String jwtToken = ServletUtil.getRequest().getHeader("Authorization");
//                    UserInfo userInfo = userProvider.get(jwtToken);
//                    personJob.setCreatorUserId(userInfo.getUserId());
//                        QueryWrapper<WorkPersonJobEntity> query = new QueryWrapper<>();
//                        query.lambda().eq(WorkPersonJobEntity::getResourcesId, personJob.getResourcesId())
//                                .eq(WorkPersonJobEntity::getJobUserId, personJob.getJobUserId())
//                                .eq(WorkPersonJobEntity::getJobinfo, personJob.getJobinfo())
//                                .eq(WorkPersonJobEntity::getType, personJob.getType());
//                        List<WorkPersonJobEntity> list = workPersonJobService.list(query);
//                        if(list.size() == 0){
                    workPersonJobService.save(personJob);
//                        }
                }

            }
        }
    }
    public void addRsfenceJob(WorkRsfenceEntity rsfence,int addDays) {
        // 获取今天是星期几（1=周一, 7=周日）
        DayOfWeek today = LocalDateTime.now().plusDays(addDays).getDayOfWeek();
        String todayStr = String.valueOf(today.getValue()); // 转为字符串："1"~"7"
        WorkResourcesEntity resources = workResourcesService.getById(rsfence.getResourcesId());
        // 判断今天的星期是否在 weekdays 中
        if (rsfence.getTime().contains(todayStr)) {
            ObjectMapper mapper = new ObjectMapper();
            mapper.registerModule(new JavaTimeModule());
            List<Map<String, String>> listTerminal = null;
            try {
                listTerminal = mapper.readValue(rsfence.getTerminal(), new TypeReference<List<Map<String, String>>>() {});
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }

            WorkPersonJobEntity personJob = new WorkPersonJobEntity();
            personJob.setType("围栏");
            personJob.setResourcesId(resources.getId());
            personJob.setLocation(resources.getLocation());
            personJob.setExecutionDate(java.sql.Date.valueOf(LocalDate.now().plusDays(addDays)));
            personJob.setExecutionStatus("未完成");
            personJob.setText(resources.getName());
            LocalDate day = LocalDate.now().plusDays(addDays);
            LocalDateTime startOfDay = day.atStartOfDay(); // 即 00:00:00
            Date dateStart = Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
            LocalDateTime endOfDay = day.atTime(23, 59, 59);
            Date dateEnd = Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
            personJob.setBegindate(dateStart);
            personJob.setEnddate(dateEnd);
            Map<String, String> jobInfo = new HashMap<>();
            jobInfo.put("notes", resources.getRemark());
            jobInfo.put("type", rsfence.getType());
            Map<String, Object> jobInfo2 = new HashMap<>();
            jobInfo2.put("option1", jobInfo);
            personJob.setJobinfo(com.alibaba.fastjson.JSONObject.toJSONString(jobInfo2));
            personJob.setEnabledMark(1);
            System.out.println("---");
            for (Map<String, String> item : listTerminal) {
                System.out.println("key: " + item.get("key"));
                System.out.println("label: " + item.get("label"));
                System.out.println("---");
                personJob.setJobUserId(item.get("key"));
                personJob.setId(UUID.randomUUID().toString());

                personJob.setCreatorTime(new Date());
//                String jwtToken = ServletUtil.getRequest().getHeader("Authorization");
//                UserInfo userInfo = userProvider.get(jwtToken);
//                personJob.setCreatorUserId(userInfo.getUserId());
//                        QueryWrapper<WorkPersonJobEntity> query = new QueryWrapper<>();
//                        query.lambda().eq(WorkPersonJobEntity::getResourcesId, personJob.getResourcesId())
//                                .eq(WorkPersonJobEntity::getJobUserId, personJob.getJobUserId())
//                                .eq(WorkPersonJobEntity::getJobinfo, personJob.getJobinfo())
//                                .eq(WorkPersonJobEntity::getType, personJob.getType());
//                        List<WorkPersonJobEntity> list = workPersonJobService.list(query);
//                        if(list.size() == 0){
                workPersonJobService.save(personJob);
//                        }
            }

        }
    }
    public void addRsgridJob(WorkRsgridEntity rsgrid,int addDays) {
        // 获取今天是星期几（1=周一, 7=周日）
        DayOfWeek today = LocalDateTime.now().plusDays(addDays).getDayOfWeek();
        String todayStr = String.valueOf(today.getValue()); // 转为字符串："1"~"7"
        // 使用 Hutool 解析 JSON 字符串
        JSONArray array = JSONUtil.parseArray(rsgrid.getTime());
        WorkResourcesEntity resources = workResourcesService.getById(rsgrid.getResourcesId());
        for (Object obj : array) {
            JSONObject item2 = (JSONObject) obj;
            String time = item2.getStr("time");
            LocalTime localTime = LocalTime.parse(time, java.time.format.DateTimeFormatter.ofPattern("HH:mm"));
            LocalDateTime dateTime = LocalDateTime.of(LocalDate.now().plusDays(addDays), localTime);
            Date date = Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant());
            String type = item2.getStr("type");
            String requirement = item2.getStr("requirement");
            List<String> weekdays = item2.getByPath("weekdays", List.class); // 自动转为 List<String>

            // 判断今天的星期是否在 weekdays 中
            if (weekdays.contains(todayStr)) {
                ObjectMapper mapper = new ObjectMapper();
                mapper.registerModule(new JavaTimeModule());
                List<Map<String, String>> listTerminal = null;
                try {
                    listTerminal = mapper.readValue(rsgrid.getTerminal(), new TypeReference<List<Map<String, String>>>() {});
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }

                WorkPersonJobEntity personJob = new WorkPersonJobEntity();
                personJob.setType("网格");
                personJob.setResourcesId(resources.getId());
                personJob.setLocation(resources.getLocation());
                personJob.setExecutionDate(java.sql.Date.valueOf(LocalDate.now().plusDays(addDays)));
                personJob.setExecutionStatus("未完成");
                personJob.setText(resources.getName());
                if("before".equals(requirement)){
                    personJob.setBegindate(date);
                }else{
                    personJob.setEnddate(date);
                }
                Map<String, String> jobInfo = new HashMap<>();
                jobInfo.put("notes", resources.getRemark());
                jobInfo.put("type", type);
                jobInfo.put("alarmType", rsgrid.getType());
                Map<String, Object> jobInfo2 = new HashMap<>();
                jobInfo2.put("option1", jobInfo);
                personJob.setJobinfo(com.alibaba.fastjson.JSONObject.toJSONString(jobInfo2));
                personJob.setEnabledMark(1);
                System.out.println("---");
                for (Map<String, String> item : listTerminal) {
                    System.out.println("key: " + item.get("key"));
                    System.out.println("label: " + item.get("label"));
                    System.out.println("---");
                    personJob.setJobUserId(item.get("key"));
                    personJob.setId(UUID.randomUUID().toString());

                    personJob.setCreatorTime(new Date());
//                    String jwtToken = ServletUtil.getRequest().getHeader("Authorization");
//                    UserInfo userInfo = userProvider.get(jwtToken);
//                    personJob.setCreatorUserId(userInfo.getUserId());
//                        QueryWrapper<WorkPersonJobEntity> query = new QueryWrapper<>();
//                        query.lambda().eq(WorkPersonJobEntity::getResourcesId, personJob.getResourcesId())
//                                .eq(WorkPersonJobEntity::getJobUserId, personJob.getJobUserId())
//                                .eq(WorkPersonJobEntity::getJobinfo, personJob.getJobinfo())
//                                .eq(WorkPersonJobEntity::getType, personJob.getType());
//                        List<WorkPersonJobEntity> list = workPersonJobService.list(query);
//                        if(list.size() == 0){
                    workPersonJobService.save(personJob);
//                        }
                }

            }
        }
    }
}
